<?php

use app\modules\Admin\models\memberwalletapplyModel;
use Illuminate\Database\Capsule\Manager as DB;
#[用户提现管理]
class WalletapplyController extends AcommonController
{
    public function init() {
        $this->model = new memberwalletapplyModel();
        $this->table = 'member_wallet_apply';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[用户提现列表]
    public function indexAction($returnData = FALSE)
    {

        $this->model = $this->model->with(['member']);
        if($this->isPost()){
            $post_data = $this->postData;
            $search_data = [];
            if(isset($post_data['mode'])){
                switch ($post_data['mode']){
                    case 'waiting':
                        array_push($search_data, ['status', '=', 0]);
                        break;
                    case 'processing':
                        array_push($search_data, ['status', '=', 1]);
                        break;
                    case 'solved':
                        array_push($search_data, ['status', '=', 2]);
                        break;
                    case 'refuse':
                        array_push($search_data, ['status', '=', -1]);
                        break;
                }
            }
            if(isset($post_data['apply_type']) && in_array($post_data['apply_type'], ['bank', 'alipay', 'wechat'])){
                array_push($search_data, ['apply_type', '=', $post_data['apply_type']]);
            }
            if(isset($post_data['apply_start']) && !empty($post_data['apply_start'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['apply_start']);
            }
            if(isset($post_data['apply_end']) && !empty($post_data['apply_end'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['apply_end']);
            }
            if(isset($post_data['option_start']) && !empty($post_data['option_start'])){
                $this->model = $this->model->whereDate('updated_at', '>=', $post_data['option_start']);
            }
            if(isset($post_data['option_end']) && !empty($post_data['option_end'])){
                $this->model = $this->model->whereDate('updated_at', '<=', $post_data['option_end']);
            }
            $keywordsTypeArray = [
                'user_id' => 'user_id',
                'user_phone' => 'user_phone'
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                if($post_data['keywordsType'] == $keywordsTypeArray['user_id'] && intval($post_data['keywords']) > 0){
                    array_push($search_data, ['member_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($search_data, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
            }
            unset($keywordsTypeArray);
            $this->search = $search_data;
            $result = parent::indexAction(true);
            if(count($result['rows'])){
                foreach ($result['rows'] as &$row){
                    $row['payable_money'] = bcsub($row['money'], $row['charge_money'], 2);
                    $row['payable_money'] = bcsub($row['payable_money'], $row['service_single_fee'], 2);
                }
            }
            json($result);
        }else{
            return parent::indexAction($returnData);
        }
    }

    #[同意提现申请]
    public function applysuccessAction()
    {
        if($this->isPost()){
            $opt_id = $this->postData['id'];
            if($this->model->where([[$this->primaryKey, $opt_id],['status', memberwalletapplyModel::STATUS_WAITING]])->exists()){
                try{
                    DB::transaction(function () use ($opt_id) {
                        $applyModel = $this->model->where([[$this->primaryKey, $opt_id],['status', memberwalletapplyModel::STATUS_WAITING]])->first();
                        $applyModel->status = memberwalletapplyModel::STATUS_SOLVED;
                        $applyModel->updated_at = timestamp();
                        $applyModel->actual_money = bcsub($applyModel->money, $applyModel->charge_money, 2);
                        $applyModel->save();
                        $log_data = [
                            'apply_id'  =>  $opt_id,
                            'event'      =>  'agree',
                            'event_id'   =>  0,
                            'remark'     =>  '同意提现申请',
                            'oper_type'  =>  'admin',
                            'oper_id'    =>  $this->auth->user_id,
                            'created_at'    =>  timestamp()
                        ];
                        \app\modules\Admin\models\memberwalletapplylogModel::addLogs($log_data);
                        $log_data['event'] = 'finished';
                        $log_data['remark'] = '已打款';
                        \app\modules\Admin\models\memberwalletapplylogModel::addLogs($log_data);
                    });
                    ret(0, '恭喜，同意提现申请成功！');
                }catch (Exception $e){
                    ret(1, '抱歉，提现申请操作失败！');
                }
            }else{
                ret(2, '操作失败，申请不存在或已处理！');
            }
            unset($log_data);
            unset($opt_id);
        }else{
            ret(500, '请求失败，非正常请求！');
        }
    }

    #[拒绝提现申请]
    public function applyrefuseAction()
    {
        if($this->isPost()){
            $opt_id = $this->postData['id'];
            $remark = $this->postData['remark']?:'无';
            $apply = $this->model->where([[$this->primaryKey, $opt_id],['status', memberwalletapplyModel::STATUS_WAITING]])->first();
            if($apply){
                $user = memberModel::where('id', $apply->member_id)->first();
                if(!$user){
                    ret(4, '操作失败，申请的用户不存在！');
                }
                try{
                    DB::transaction(function () use ($apply, $remark, $user) {
                        DB::table($this->table)->where([[$this->primaryKey, $apply->id],['status', memberwalletapplyModel::STATUS_WAITING]])
                            ->update(['status' =>memberwalletapplyModel::STATUS_REFUSE, 'remark' => $remark, 'updated_at' => timestamp()]);
                        //临时进行用户余额变动
//                        memberModel::money($apply->money, $apply->member_id, 'cash_error', $apply->id);等果果修改后再调用
                        //临时变动 START
                        $user_before_money = $user->money;
                        $user_after_money = $user->money + $apply->money;
                        $opt_time = timestamp();
                        $user->money = $user_after_money;
                        $user->updated_at = $opt_time;
                        $user->save();
                        membermoneylogModel::query()->insert([
                            'member_id'     =>  $apply->member_id,
                            'event'         =>  'withdrawdenied',
                            'event_id'      =>  $apply->id,
                            'before'        =>  $user_before_money,
                            'money'         =>  $apply->money,
                            'after'         =>  $user_after_money,
                            'remark'        =>  '拒绝用户提现申请，退回资金',
                            'oper_type'     =>  'admin',
                            'oper_id'       =>  $this->auth->user_id,
                            'created_at'    =>  $opt_time
                        ]);
                        //临时变动 END
                        $log_data = [
                            'apply_id'  =>  $apply->id,
                            'event'      =>  'denied',
                            'event_id'   =>  0,
                            'remark'     =>  '拒绝原因：'.$remark,
                            'oper_type'  =>  'admin',
                            'oper_id'    =>  $this->auth->user_id,
                            'created_at'    =>  $opt_time
                        ];
                        \app\modules\Admin\models\memberwalletapplylogModel::addLogs($log_data);
                    });
                    ret(0, '恭喜，拒绝提现申请操作成功！');
                }catch (Exception $e){
                    ret(1, '抱歉，提现申请操作失败！');
                }
            }else{
                ret(2, '操作失败，申请记录不存在或已处理！');
            }
            unset($log_data);
            unset($remark);
        }else{
            ret(500, '请求失败，非正常请求！');
        }
    }

    #[提现记录导出]
    public function exportAction()
    {
        $type     = $this->get('keywordsType');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $optionStartOn = $this->get('option_start_on');
        $optionEndOn = $this->get('option_end_on');
        $mode = $this->get('mode');
        $apply_type = $this->get('apply_type');

        $dirpath = APP_PATH . '/public/excel/';
        if ($dirpath !== '.' && !file_exists($dirpath)) {
            mkdir($dirpath, 0777, true);
        }
        $filename = 'WalletApply' . date('Ymd') . uniqid() . '.xlsx';
        $filepath = $dirpath . $filename;
        $res = exec("php ". APP_PATH . "/public/cli.php export/walletapply \"mode={$mode}&type={$type}&apply_type={$apply_type}&keywords={$keywords}&start_on={$startOn}&end_on={$endOn}&option_start_on={$optionStartOn}&option_end_on={$optionEndOn}&path={$filepath}\"");
        if ($res === 'Done' && file_exists($dirpath . $filename)) {
			if( $webpath = syncFile($filepath) ){
                ret(0, '提现记录导出excel成功', $webpath);
            }
        }
        ret(30003, '提现记录导出失败');
    }
}